from django.shortcuts import render
from rest_framework.generics import ListAPIView,CreateAPIView,DestroyAPIView,UpdateAPIView
from .serializers import CollectionSerializer
from rest_framework.permissions import IsAuthenticated
from .models import ArticleCollection,Article
from rest_framework.response import Response
from django.utils import timezone as datetime
from rest_framework import status
# Create your views here.
class CollecionListAPIView(ListAPIView,CreateAPIView,DestroyAPIView,UpdateAPIView):

    serializer_class = CollectionSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):

        user = self.request.user
        ret =  ArticleCollection.objects.filter(is_deleted=False, is_show=True, user=self.request.user).order_by("orders","id")
        if len(ret)<1:
            collection1 = ArticleCollection.objects.create(
                user=user,
                name="日记本",
                orders=1,
            )

            collection2 = ArticleCollection.objects.create(
                user=user,
                name="随笔",
                orders=2,
            )

            ret = [
                collection1,
                collection2,
            ]

        return ret

    def perform_destroy(self, instance):

        instance.is_deleted = True
        instance.save()

from .serializers import ArticleSerializer
class ArticleAPIView(ListAPIView,IsAuthenticated,CreateAPIView,DestroyAPIView,UpdateAPIView):

    serializer_class = ArticleSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):

        collection_id = self.kwargs.get("collection")
        article_list = Article.objects.filter(is_deleted=False, is_show=True, user=self.request.user,collection_id = collection_id).order_by("orders","id")
        return article_list

    def perform_destroy(self, instance):

        instance.is_deleted = True
        instance.save()

    def patch(self, request, pk):

        try:
            article = Article.objects.get(is_deleted=False, is_show=True, user=self.request.user,pk=pk)
            if request.data.get("pub_time"):
                pub_time = request.data.get("pub_time")
                if article.is_public:
                    return Response({"detail":'已经发布的文章不能在进行定时发布'})
                now_time = datetime.now().timestamp()
                time_stamp = datetime.datetime.strptime(pub_time,'%Y-%m-%d %H:%M').timestamp()
                if time_stamp<now_time:
                    return Response({"detail":'瞎几把点什么，看看今天几号了'})
                article.pub_date = pub_time
                article.save()
                return Response({"detail":'定时成功'})
            else:
                article.is_public = not article.is_public
                article.save()
                return Response({"detail":"状态更改成功"})
        except Article.DoesNotExist:
            return Response({"detail":"文章不存在了"})

    def put(self,request,pk):

        try:
            article = Article.objects.get(is_deleted=False, is_show=True, user=self.request.user,pk=pk)
            collection_id = int(request.data.get("c_id"))
            article.collection_id = collection_id
            article.save()
            print("try")
            return Response({"detail":"移动成功"})
        except Article.DoesNotExist:
            print("except")
            return Response({"detail":"文章不存在"})

class AriticleContentAPIView(UpdateAPIView,IsAuthenticated):

    serializer_class = ArticleSerializer
    queryset = Article.objects.all()
    permission_classes = [IsAuthenticated]

    def put(self,request,pk):

        try:
            article = Article.objects.get(user = self.request.user,id = pk)
            title = request.data.get("title")
            content = request.data.get("content")
            html_content = request.data.get("html_content")
            article.title = title
            article.content = content
            article.html_content = html_content
            article.save()
            return Response({"detail":"保存成功"})
        except Article.DoesNotExist:
            return Response({"detail":"文章不存在"})

from .models import ArticleImage
from .serializers import ArticleImageSerializer
class ArticleImageAPIView(CreateAPIView):
    queryset = ArticleImage.objects.all()
    serializer_class = ArticleImageSerializer

from .models import ArticleSpecial,ArticlePostSpecial
from .serializers import ArticleSpecialSerializer
class ArticleSpecilAPIView(ListAPIView,IsAuthenticated):

    permission_classes = [IsAuthenticated]
    serializer_class = ArticleSpecialSerializer

    def get_queryset(self):

        article_id = self.request.query_params.get("article_id")
        # print(self.request.query_params,article_id,self.request.data.get("article_id"))
        special_list = ArticleSpecial.objects.filter(is_deleted=False, is_show=True, mymanager__user=self.request.user).order_by("orders", "id")
        for special in special_list:
            special.post_status = special.check_post_stauts(article_id)
        return special_list

from rest_framework.views import APIView
class ArticlePostSpecliAPIView(APIView):

    permission_classes = [IsAuthenticated]

    def post(self, request):

        article_id = request.data.get("article_id")
        specil_id = request.data.get("specil_id")
        try:
            article = Article.objects.get(pk=article_id, is_show=True, is_deleted=False, user=self.request.user)
        except Article.DoesNotExist:
            return Response({"detail": "文章不存在"}, status=status.HTTP_400_BAD_REQUEST)
        try:
            special = ArticleSpecial.objects.get(pk=specil_id, is_show=True, is_deleted=False, user=self.request.user)
        except ArticleSpecial.DoesNotExist:
            return Response({"detail": "文集不存在"}, status=status.HTTP_400_BAD_REQUEST)
        try:
            ArticlePostSpecial.objects.get(article=article, special=special, status__in=[0, 1, 2])
            return Response({"detail": "文章已经收录了"}, status=status.HTTP_400_BAD_REQUEST)
        except:
            pass
        post_article = ArticlePostSpecial.objects.create(
            article=article,
            special=special,
            status=0,
            post_time=datetime.now()
        )
        try:
            # 当前投稿文章作者是专题管理员
            post_article.special.mymanager.get(user=request.user)
            post_article.status = 2  # 默认审核通过
            post_article.save()
        except:
            pass

            # 返回响应信息
        return Response({"detail": "投稿成功！"})

from rest_framework.generics import RetrieveAPIView
from .serializers import ArticleInfoSerializer
class ArticleInfoAPIView(RetrieveAPIView):

    serializer_class = ArticleInfoSerializer
    queryset = Article.objects.filter(is_deleted=False,is_show=True,is_public=True,)
